package com.hboxs.asl.controller.app.member;

import com.hboxs.asl.*;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.BankCard;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.Trade;
import com.hboxs.asl.entity.Withdrawal;
import com.hboxs.asl.service.*;
import com.hboxs.asl.util.BankUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Controller(value = "appWalletFavorController")
@RequestMapping(value = "/app/m/wallet")
public class WalletControl extends BaseController {

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "tradeServiceImpl")
    private TradeService tradeService;
    @Resource(name = "bankCardServiceImpl")
    private BankCardService bankCardService;
    @Resource(name = "withdrawalServiceImpl")
    private WithdrawalService withdrawalService;

    /**
     * 我的钱包首页
     *
     * @return json
     */
    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public
    @ResponseBody
    Object index(Pageable pageable) {

        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            pageable.getFilters().add(Filter.eq("member", member));
            Page page = tradeService.findPage(pageable);

            return JsonMessage.success(

                    "totalPage", page.getTotalPages()

                    , "pageNumber", page.getPageNumber()

                    , "pageSize", page.getPageSize()

                    , "total", page.getTotal()

                    , "point" , member.getPoint()

                    , "balance", member.getBalance()

                    , "trades", JsonMessage.optimiseObj(page.getContent(), "completeDate", "amount")
            );

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 添加银行卡
     *
     * @param bankCard
     * @return
     */
    @RequestMapping(value = "/addBankCard", method = RequestMethod.POST)
    public
    @ResponseBody
    Object addBankCard(BankCard bankCard) {
        if (!isValid(bankCard)) {
            return JsonMessage.error("数据错误");
        }
        Member member = memberService.getCurrentByToken();
        if(member == null) {
            return JsonMessage.USER_NOT_LOGIN;
        }
        if (bankCardService.findBankCardByNumber(bankCard.getCardNumber()) != null) {
            return JsonMessage.error("银行卡已存在");
        }

        String code = BankUtils.validateAndCacheCardInfo(bankCard.getCardNumber());
        if (code == null) {
            return JsonMessage.error("无法识别银行卡所属银行名称");
        }

        bankCard.setCode(code.toLowerCase());
        bankCard.setMember(member);
        bankCardService.save(bankCard);
        return JsonMessage.success("提交成功");
    }

    /**
     * 解绑银行卡
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteBankCard", method = RequestMethod.GET)
    public
    @ResponseBody
    Object deleteBankCard(Long id) {
        Member member = memberService.getCurrentByToken();

        if(member == null) {
            return JsonMessage.USER_NOT_LOGIN;
        }

        BankCard bankCard = bankCardService.find(id);
        if (bankCard == null || bankCard.getMember() != member) {
            return JsonMessage.error("找不到银行卡");
        }

        bankCardService.delete(bankCard);
        return JsonMessage.success("解绑成功");
    }

    /**
     * 我的银行卡
     *
     * @return
     */
    @RequestMapping(value = "/myBankCards", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage myBankCards(Pageable pageable) {
        Member member = memberService.getCurrentByToken();
        if(member == null) {
            return JsonMessage.USER_NOT_LOGIN;
        }
        Page<BankCard> page = bankCardService.findPage(member, pageable);
        return JsonMessage.success(
                "totalPage", page.getTotalPages(),
                "pageNumber", page.getPageNumber(),
                "pageSize", page.getPageSize(),
                "total", page.getTotal(),
                "content", JsonMessage.optimiseObj(page.getContent(), "id", "name", "cardNumber", "subBranch", "type", "icon"));
    }

    /**
     * 申请提现
     *
     * @return
     */
    @RequestMapping(value = "/submitWithdrawal", method = RequestMethod.POST)
    public
    @ResponseBody
    Object submitWithdrawal(Long bankCardId, BigDecimal amount) {
        Member member = memberService.getCurrentByToken();
        BankCard bankCard = bankCardService.find(bankCardId);

        // 银行卡错误
        if (bankCard == null || bankCard.getMember() != member || amount == null) {
            return JsonMessage.error("数据错误");
        }

        Withdrawal withdrawal = new Withdrawal();
        withdrawal.setMember(member);
        withdrawal.setStatus(Withdrawal.Status.reviewing);
        withdrawal.setBankCardName(bankCard.getName());
        withdrawal.setBankCardNo(bankCard.getCardNumber());
        withdrawal.setBankCardSubBranch(bankCard.getSubBranch());
        withdrawal.setPoint(amount);
        withdrawalService.save(withdrawal);
        //用户余额减少
        member.setBalance(member.getBalance().subtract(amount));

        memberService.update(member);

        return JsonMessage.success("申请成功");
    }


    /**
     * 我的提现记录
     *
     * @return
     */
    @RequestMapping(value = "/myWithdrawals", method = RequestMethod.GET)
    public
    @ResponseBody
    Object withdrawalList(Pageable pageable) {

        Page<Withdrawal> page = withdrawalService.findPageByMember(pageable, memberService.getCurrentByToken());

        return JsonMessage.success(

                "totalPage", page.getTotalPages(),

                "pageNumber", page.getPageNumber(),

                "pageSize", page.getPageSize(),

                "total", page.getTotal(),

                "content", JsonMessage.optimiseObj(
                        page.getContent(),
                        "id" ,"rejectReason" , "status",
                        "bankCardNo", "bankCardName", "bankCardSubBranch","createDateF", "point"
                )
        );

    }

    /**
     * 我的充值记录
     * @return
     */
    @RequestMapping(value = "/charge_records", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage chargeRecords(Pageable pageable) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }

            Page<Trade> page = tradeService.findPageSuccess(pageable, member);

            return JsonMessage.success(

                    "totalPage", page.getTotalPages(),

                    "pageNumber", page.getPageNumber(),

                    "pageSize", page.getPageSize(),

                    "total", page.getTotal(),

                    "content", JsonMessage.optimiseObj(
                            page.getContent(),"tn", "amount", "createDateF"
                    )
            );

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}
